﻿using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ConferenceLogInfo")]
	public class ConferenceLogInfoController : BaseDbController
	{
		[Route("Index/{ConferenceId}")]
		public async Task<ActionResult> Index(string conferenceId)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceId);

			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常 &&
						x.ID == conferenceId);

			ViewBag.ConferenceId = conferenceId;
			ViewBag.ConferenceName = conferenceMaster.ConferenceName;
			ViewBag.ControllerName = Resources.ConferenceLogInfo;
			ViewBag.Language = conferenceMaster.IsInternational ? ConstValues.Language.En : ConstValues.Language.Cn;

			var model = new ConferenceLogInfoModel();
			model.ConferenceId = conferenceId;
			LoginUser.ConferenceFunctionIdList = Utility.GetConferenceFunctionIdList(conferenceId);
			return View(model);
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, ConferenceLogInfoModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = DbContext.LogInfo.AsNoTracking()
					.Where(x => x.ConferenceId == model.ConferenceId);

			if (!string.IsNullOrWhiteSpace(model.selAction))
			{
				sql = sql.Where(x => x.Action.Contains(model.selAction));
			}

			if (!string.IsNullOrWhiteSpace(model.selView))
			{
				sql = sql.Where(x => x.View.Contains(model.selView));
			}

			if (!string.IsNullOrWhiteSpace(model.selController))
			{
				sql = sql.Where(x => x.Controller.Contains(model.selController));
			}

			int total = await sql.CountAsync();
			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderBy(x => x.Sort).ThenByDescending(x => x.UpdateDate).ThenBy(x => x.View).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();
			var result = sqlResult.Select(x => new
			{
				ID = x.ID,
				PageLogsType = x.PageLogsType,
				Action = x.Action,
				View = x.View,
				Controller = x.Controller,
				Path = x.Path,
				Client = x.Client,
				Status = x.Status,
				Sort = x.Sort,
				Remark = x.Remark,
				CreateDate = Request.Cookies["_culture"].Value == ConstValues.Language.Cn ?
						x.CreateDate.Value.ToString("yyyy-MM-dd") :
						x.CreateDate.Value.ToString("MM/dd/yyyy"),
				CreateIP = x.CreateIP,
				Creator = x.Creator
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}
	}
}